package com.ns.scs.task.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ns.core.current.config.SymbolsMark;
import com.ns.scs.task.dto.ScheduledLogsPageDto;
import com.ns.scs.task.entity.ScheduledTaskLogs;
import com.ns.scs.task.mapper.ScheduledTaskLogsMapper;
import com.ns.scs.task.service.IScheduledTaskLogsService;
import com.ns.scs.task.vo.ScheduledTaskLogsVO;
import com.ns.scs.task.vo.ScheduledTaskVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 定时任务逻辑实现
 *
 * @author liao.wei
 * @since 2024/11/11
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ScheduledTaskLogsServiceImpl extends ServiceImpl<ScheduledTaskLogsMapper, ScheduledTaskLogs> implements IScheduledTaskLogsService {

    private final ScheduledTaskLogsMapper mapper;

    @Override
    public Page<ScheduledTaskLogsVO> getList(ScheduledLogsPageDto dto) {
        return mapper.getList(dto, new Page<>(dto.getCurrent(), dto.getSize()));
    }

    @Override
    public String saveLogs(ScheduledTaskVO scheduledTask, int result, Exception e) {
        ScheduledTaskLogs logs = new ScheduledTaskLogs();
        BeanUtils.copyProperties(scheduledTask, logs);
        logs.setId(null);
        logs.setTaskId(scheduledTask.getId());
        String msg = "任务id【" + scheduledTask.getId() + "】,任务名称【" + scheduledTask.getTaskName() + "】";
        String note = "";
        if (Objects.equals(result, SymbolsMark.TWO)) {
            msg += ",执行成功1条！";
        } else if (Objects.equals(result, SymbolsMark.ONE)) {
            msg += ",执行失败1条！";
            note = e.getMessage();
        }
        logs.setLogs(msg);
        logs.setNote(note);
        logs.setStatus(result);
        mapper.insertOrUpdate(logs);
        return msg;
    }
}